package top.infopub.io.impl;


import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;

import top.infopub.io.ContentHandler;


/**
 * read properties  
 * @author Awoke
 * @version 2018年9月13日
 * @see ConfigPropertiesContentHandler
 * @since
 */
public class ConfigPropertiesContentHandler implements ContentHandler<Map<String, String>> {

    private static Pattern p = Pattern.compile("^[A-Za-z0-9\\.\\@)!#-]+$");

    Map<String, String> result = new LinkedHashMap<String, String>();

    @Override
    public void contentHandler(String line) {
        String[] pvs = line.split("=");
        if (pvs.length != 2) {
            return;
        }
        result.put(pvs[0], unicode2String(pvs[1]));
    }

    @Override
    public Map<String, String> result() {
        return result;
    }

    private String unicode2String(String str) {
        if (str == null || str.length() == 0) {
            return "";
        }
        if (p.matcher(str).matches()) {
            return str;
        }
        StringBuilder sb = new StringBuilder(1000);
        // 临时变量  
        int hexNumber;
        char c;
        String hexStr;
        for (int i = 0; i < str.length(); i++ ) {
            // 加上前缀  
            sb.append("\\u");
            // 取出第i为的char字符  
            c = str.charAt(i);
            // 取出高8位  
            hexNumber = (c >>> 8);
            hexStr = Integer.toHexString(hexNumber);
            if (hexStr.length() == 1) {
                sb.append("0");
            }
            sb.append(hexStr);

            // 取出低8位  
            hexNumber = (c & 0xFF);
            hexStr = Integer.toHexString(hexNumber);
            if (hexStr.length() == 1) {
                sb.append("0");
            }
            sb.append(hexStr);
        }
        return sb.toString();
    }

}
